const state = {
  config: null,
  sockets: {},
  messages: {},
  isConnecteds: {},
  reconnectErrors: {},
};
const mutations = {
  SET_CONFIG(state, config) {
    state.config = config;
  },
  SET_SOCKET(state, { ws_url, socket }) {
    state.sockets[ws_url] = socket;
  },
  ADD_MESSAGE(state, { ws_url, message }) {
    if (!state.messages[ws_url]) {
      // state.messages[ws_url] = [];
      this._vm.$set(state.messages, ws_url, []);
    }
    const newMessages = [...state.messages[ws_url], message].slice(-100);
    this._vm.$set(state.messages, ws_url, newMessages);
    // state.messages[ws_url].push(message);
    // // 数组最多保留100条记录
    // if (state.messages[ws_url].length > 100) {
    //   state.messages[ws_url].shift();
    // }
    // console.log(state.messages);
  },
  SET_CONNECTED(state, { ws_url, isConnected }) {
    state.isConnecteds[ws_url] = isConnected;
  },
  SET_RECONNECT_ERROR(state, { ws_url, reconnectError }) {
    state.reconnectErrors[ws_url] = reconnectError;
  },
};
const actions = {
  connect({ commit, dispatch }, ws_url) {
    if (state.sockets[ws_url]) {
      console.log('Already connected to this URL:', ws_url);
      return;
    }
    const socket = new WebSocket(`${ws_url}`);

    socket.onopen = () => {
      console.log('已连接到 WebSocket 服务器:', ws_url);
      commit('SET_CONNECTED', { ws_url, isConnected: true });
      commit('SET_RECONNECT_ERROR', { ws_url, reconnectError: false });
      commit('SET_SOCKET', { ws_url, socket });
    };

    socket.onmessage = (event) => {
      if (
        `${process.env.VUE_APP_WEBSOCKET_URL}/${JSON.parse(event.data).cameraId}` ===
        ws_url
      ) {
        // console.log('WebSocket 服务器:', ws_url, event.data);
        commit('ADD_MESSAGE', { ws_url, message: event.data });
      }
    };

    socket.onclose = () => {
      console.log('已断开与 WebSocket 服务器的连接');
      commit('SET_CONNECTED', { ws_url, isConnected: false });
      commit('SET_RECONNECT_ERROR', { ws_url, reconnectError: true });
      delete state.sockets[ws_url];
      // 尝试重新连接
      setTimeout(() => {
        dispatch('connect', ws_url);
      }, 5000);
    };

    socket.onerror = (error) => {
      console.error('WebSocket 错误:', error);
      commit('SET_RECONNECT_ERROR', { ws_url, reconnectError: true });
    };
  },
  close({ state }, ws_url) {
    const socket = state.sockets[ws_url];
    if (socket) {
      socket.close();
      delete state.sockets[ws_url];
      delete state.messages[ws_url];
      delete state.isConnecteds[ws_url];
      delete state.reconnectErrors[ws_url];
    }
  },
  sendMessage({ state }, { ws_url, message }) {
    const socket = state.sockets[ws_url];
    console.log(socket, state.isConnecteds);
    if (socket && state.isConnecteds[ws_url]) {
      try {
        // 将对象转换为 JSON 字符串
        const messageString = JSON.stringify(message);
        socket.send(messageString);
      } catch (error) {
        // 不是对象直接发送字符串
        console.error('发送消息时发生错误:', error);
        socket.send(message);
      }
    } else {
      console.error('WebSocket 未连接');
    }
  },
};
const getters = {
  socket: (state) => (ws_url) => state.sockets[ws_url],
  config: (state) => state.config,
  messages: (state) => (ws_url) => state.messages[ws_url] || [],
  isConnected: (state) => (ws_url) => state.isConnecteds[ws_url],
  reconnectError: (state) => (ws_url) => state.reconnectErrors[ws_url],
};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
};
